/**
 *    Copyright 2015 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.jfinal.plugin.activerecord.freemarker;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Applies provided parameter(s) to FreeMarker template.
 * Then passes the result into default MyBatis engine (and it finally replaces #{}-params to '?'-params).
 * So, FreeMarker is used as preprocessor for MyBatis engine.
 *
 * @author huangx
 */
@SuppressWarnings("unchecked")
public class FreeMarkerSql {
	private final Template template;

	public final static String GENERATED_PARAMS_KEY = "__GENERATED__";

	public FreeMarkerSql(Template template) {
		this.template = template;
	}

	public String getBoundSql(Object parameterObject) {
		// Add to passed parameterObject our predefined directive - MyBatisParamDirective
		// It will be available as "p" inside templates
		
		List<Object> generatedParams = new ArrayList<Object>();
		Map<String, Object> dataModel = (Map<String, Object>) parameterObject;

		if (parameterObject == null) {
			dataModel = new HashMap<String, Object>(2);
		}
		dataModel.put(GENERATED_PARAMS_KEY, generatedParams);
		dataModel.put(MyBatisParamDirective.DEFAULT_KEY, new MyBatisParamDirective());

		CharArrayWriter writer = new CharArrayWriter();
		try {
			template.process(dataModel, writer);
		} catch (TemplateException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		// We got SQL ready for MyBatis here. This SQL contains params declarations like "#{param}",
		// they will be replaced to '?' by MyBatis engine further
		String sql = writer.toString();
		System.out.println("sql:" + sql);

		return null;
	}
}
